const mongoose = require('mongoose');

const BloodPressureSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
      index: true
    },
    systolic: {
      type: Number,
      required: true,
      min: [60, '收缩压不能低于60 mmHg'],
      max: [250, '收缩压不能超过250 mmHg']
    },
    diastolic: {
      type: Number,
      required: true,
      min: [40, '舒张压不能低于40 mmHg'],
      max: [150, '舒张压不能超过150 mmHg']
    },
    pulse: {
      type: Number,
      min: [30, '脉搏不能低于30次/分'],
      max: [220, '脉搏不能超过220次/分']
    },
    measuredAt: {
      type: Date,
      required: true,
      default: Date.now
    },
    measuredArm: {
      type: String,
      enum: ['左臂', '右臂'],
      default: '左臂'
    },
    bodyPosition: {
      type: String,
      enum: ['坐姿', '卧姿', '站姿'],
      default: '坐姿'
    },
    notes: {
      type: String,
      maxlength: 500
    },
    tags: [String],
    isManualEntry: {
      type: Boolean,
      default: true
    },
    deviceInfo: {
      type: String
    },
    abnormal: {
      type: Boolean,
      default: false
    },
    category: {
      type: String,
      enum: ['正常', '正常高值', '一级高血压', '二级高血压', '三级高血压', '低血压', '收缩期高血压', ''],
      default: ''
    }
  },
  {
    timestamps: true
  }
);

// 创建复合索引，加速按用户和时间范围查询
BloodPressureSchema.index({ user: 1, measuredAt: -1 });

// 在保存前计算血压类别
BloodPressureSchema.pre('save', function(next) {
  const systolic = this.systolic;
  const diastolic = this.diastolic;
  
  // 按照中国高血压指南分类
  if (systolic < 90 || diastolic < 60) {
    this.abnormal = true;
    this.category = '低血压';
  } else if (systolic >= 180 || diastolic >= 110) {
    this.abnormal = true;
    this.category = '三级高血压';
  } else if (systolic >= 160 || diastolic >= 100) {
    this.abnormal = true;
    this.category = '二级高血压';
  } else if (systolic >= 140 || diastolic >= 90) {
    this.abnormal = true;
    this.category = '一级高血压';
  } else if ((systolic >= 130 && systolic < 140) || (diastolic >= 85 && diastolic < 90)) {
    this.abnormal = true;
    this.category = '正常高值';
  } else if (systolic >= 140 && diastolic < 90) {
    this.abnormal = true;
    this.category = '收缩期高血压';
  } else {
    this.abnormal = false;
    this.category = '正常';
  }
  
  next();
});

module.exports = mongoose.model('BloodPressure', BloodPressureSchema); 